﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint);
    InitMap();
    InitIot();
    ui->stackedWidget->setCurrentIndex(0);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitIot(){
    Iot = new iot(this);
    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&MainWindow::onTimeOut);
    timer->setInterval(500);
}

void MainWindow::InitMap()
{
    map = new Map(this);
    ui->stackedWidget->insertWidget(1,map);
    connect(map->gotoMain,&QPushButton::clicked,[=](){
        ui->stackedWidget->setCurrentIndex(0);
    });
}

void MainWindow::on_getToken_clicked()
{
    token = "";
    QString tipMes;
    token = Iot->getAccessToken();
    if(token == ""){
        qDebug()<<"获取token失败！";
    }
    else {
        qDebug()<<"获取token成功!";
        isLink = Iot->getDeviceStatus(token);
        if(isLink){
            ui->isLink->setText("在线");
            qDebug()<<"设备在线";
            timer->start();
        }
        else {
            ui->isLink->setText("离线");
            qDebug()<<"设备不在线";
        }
    }
}

void MainWindow::onTimeOut(){
    if(token != ""){
        isLink = Iot->getDeviceStatus(token);
        if(isLink){
            ui->isLink->setText("在线");
            QJsonObject obj = Iot->getDeviceShadowData(token);
            temperature = obj["temperature"].toInt();
            humidity = obj["humidity"].toInt();
            windVelocity = obj["windVelocity"].toDouble();
            windDirect = obj["windDirect"].toString();
            isCar = obj["isCar"].toBool();
            isDrone = obj["isDrone"].toBool();
            
            ui->temperature->setText(QString(" %1 ℃").arg(temperature));
            ui->humidity->setText(QString(" %1 %").arg(humidity));
            ui->windVelocity->setText(QString(" %1 m/s").arg(windDirect));
            ui->windDirect->setText(QString(" %1 ").arg(windVelocity));
            
        }
        else ui->isLink->setText("离线");
    }
}

void MainWindow::on_gotoMap_clicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}


void MainWindow::on_exit_clicked()
{
    exit(0);
}
